package com.nit.lab.service.ship.Impl;

import com.nit.lab.dto.ship.WorkDTO;
import com.nit.lab.dto.utils.OpResultDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.ship.ShipEntity;
import com.nit.lab.entity.ship.WorkEntity;
import com.nit.lab.mapper.ship.ShipMapper;
import com.nit.lab.mapper.ship.WorkMapper;
import com.nit.lab.service.ship.WorkService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class WorkServiceImpl implements WorkService {

    @Autowired(required = false)
    private WorkMapper workMapper;


    @Override
    public TableRspDTO query(TableReqDTO tableReqDTO) throws Exception {
        Long count = workMapper.count4Table();
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                workMapper.query(null));
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    public OpResultDTO queryWorkType() throws Exception {
        OpResultDTO opResultDTO = new OpResultDTO();
        opResultDTO.setResult(workMapper.queryWorkType());
        return opResultDTO;
    }

    @Override
    public Integer add(WorkDTO workDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        WorkEntity workEntity = mapperFactory.getMapperFacade().map(workDTO, WorkEntity.class);
        workEntity.setGmtCreate(new Date());
        return workMapper.add(workEntity);
    }

    @Override
    public Integer update(WorkDTO workDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        WorkEntity workEntity = mapperFactory.getMapperFacade().map(workDTO, WorkEntity.class);
        return workMapper.update(workEntity);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String workIds) throws Exception {
        String[] arrayWorkId = workIds.split(",");
        for (int i = 0; i < arrayWorkId.length; i++) {
            workMapper.remove(Long.parseLong(arrayWorkId[i]));
        }
        return arrayWorkId.length;
    }
}
